Version 1.0 (08 August 2017)

Prerequisities

Prerequisities 1

What to know?

  1. Basic R skills
  2. Basic Unix/Linux skills

What to bring?

  1. Bring laptop
  2. A GitHub account?

Prerequisities 2

Which R packages to install/load?

pkg <- c("ggplot2", "rmarkdown", "knitr", "dplyr");
lapply(pkg, function(x) { if (!require(x, character.only = TRUE, quietly = TRUE)) {
  install.packages(x);
  require(x, quietly = TRUE)}
})

What data to work with?

We will use the starwars dataset from dplyr.

head(starwars, n = 4);
## # A tibble: 4 x 13
##             name height  mass hair_color  skin_color eye_color birth_year
##            <chr>  <int> <dbl>      <chr>       <chr>     <chr>      <dbl>
## 1 Luke Skywalker    172    77      blond        fair      blue       19.0
## 2          C-3PO    167    75       <NA>        gold    yellow      112.0
## 3          R2-D2     96    32       <NA> white, blue       red       33.0
## 4    Darth Vader    202   136       none       white    yellow       41.9
## # ... with 6 more variables: gender <chr>, homeworld <chr>, species <chr>,
## #   films <list>, vehicles <list>, starships <list>

How to get started 1

Create new R Markdown document in RStudio

  1. File \(\rightarrow\) New File \(\rightarrow\) R Markdown

How to get started 2

  1. Specify output option

  2. Render

Exercise

  1. Create a new R Markdown document in RStudio.
  2. Select PDF, HTML and Word as output option.
  3. Render the Markdown document to the corresponding output formats.
  4. Locate and open the final output file.

Under the hood

Document conversion

  1. Rmd -> PDF, HTML, Word uses rmarkdown::render() (knitr::pandoc() is deprecated)
  2. rmarkdown::render() makes use of the universal document converter pandoc (installed as part of RStudio)

For example, pandoc will translate

# Header

into the following output-specific lines:

  1. For HTML output

    <h1>Header</h1>
  2. For \(\LaTeX\) output

    \section{Header}

(R) Markdown 101

(R) Markdown 101

Beware the different Markdown flavours: GitHub, R Markdown, vanilla Markdown, …

Focus here on R Markdown.

  1. Headers
  2. Emphasis: bold and italics
  3. Lists: Ordered and unordered
  4. Images and links
  5. Blockquotes
  6. Rules and line breaks

More details:

(R) Markdown 101

Headers

# Header 1
## Header 2
### Header 3
#### Header 4

Emphasis

*italic*, _italic_
**bold**, __bold__

Lists

1. Level 1
    + Item 1
    + Item 2
2. Level 2
    + Item 3
    + Item 4
3. Level 3

Images and links

![Alt text](URL)
[RStudio](https://www.rstudio.com/)
[email@email.com](mailto:email@email.com)

Blockquote

> RStudio makes R easier to use. It includes a 
  code editor, debugging & visualization tools.

Rules

----, ****

Manual line breaks
End line with two or more whitespaces.

Line 1 ends here,␣␣
line 2 start here.

(R) Markdown 101

Tables
Assemble list of words, and divide them with hyphens - (for the first row), and then separating each column with a pipe |.

First Header | Second Header
------------ | -------------
Cell 1 | Cell 2
Cell 3 | cell 4

Fenced code blocks
Lines wrapped within an environment with leading and tailing ``` are converted into a code block.
An optional language identifier provides syntax highlighting.

```bash
echo "3 + 4"
```

R code blocks will be evaluated and printed (replace double with single curly brackets).

```{{r}}
3 + 4
```

Inline code
Use single backticks ` (delete curly brackets)

`{r} summary(starwars)`

Equations
The power of \(\LaTeX\)

$x = a$
$$ int_{x=0}^\infty dx \log{1+x} $$

Exercise

  1. Experiment with different markdown elements in your markdown document
  2. Render the document and check the resulting output file
  3. Are there any specific text elements you would like to typeset?

(R) Markdown 101: Images

More options to include to include external images/figures.

  1. Use ![](path/to/image.png)
  2. Use HTML <img src="path/to/image.png" style="width:200px;">
  3. Use knitr::include_graphics

R Markdown elements

R Markdown output

The YAML header

---
title: "Main title"
subtitle: "Subtitle"
author: "Firstname Lastname"
date: "07/08/2017"
output:
  word_document
---

Main keys

  1. Title and subtitle
  2. Author (can have multiple authors as list for key author)
  3. Date (can be R code, e.g. format(Sys.time(), '%d %B %Y'))
  4. Output option: html_document, pdf_document, word_document, ioslides_presentation, beamer_presentation

Exercise: Change the title/author/date/output fields of your Rmd document.

Controlling the R output: Code chunk options

Some useful options

  • eval=FALSE: Don't run code.
  • include=FALSE: Run code but don't include the chunk in the output document.
  • echo=FALSE: Don't show code, show results.
  • results='hide': Show code, don't show results.
  • message=FALSE: Don't show any additional R messages.
  • error=FALSE: Don't show R error messages.
  • warning=FALSE: Don't show R warning messages.
  • cache=TRUE: Use cached results (if available) until the code chunk is changed.
  • fig.width=7, fig.height=7: Set figure width and height to 7 inches.

More chunk options can be found in e.g. the R Markdown Reference Guide.

Exercise: Experiment with different code options: Disable output, results, and code evaluation.

Tables

  1. General: How to output tables/dataframes?
  2. knitr::kable()
  3. tibble::print.tbl_df()
  4. DT::datatable()

Excercise: Output a table, and use different layout options.

Tables: knitr::kable()

suppressMessages(library(knitr));
kable(starwars[1:4, 1:4])
name height mass hair_color
Luke Skywalker 172 77 blond
C-3PO 167 75 NA
R2-D2 96 32 NA
Darth Vader 202 136 none

Tables: DT::datatable()

suppressMessages(library(DT));
#DT::datatable(starwars, options = list(dom = "ftp", scrollX = TRUE, pageLength = 4));
DT::datatable(starwars[, 1:4], options = list(pageLength = 8));

Interactive plots

  1. plotly
  2. D3 in R

Load the necessary libraries

suppressMessages(library(ggplot2));
suppressMessages(library(plotly));
## Warning: package 'plotly' was built under R version 3.4.1
suppressMessages(library(scatterD3));

Interactive plots: plotly::ggplotly()

ggplotly(ggplot(starwars, aes(x = height, y = mass, label = name)) + geom_point(), height = 5);

Interactive plots: scatterD3::scatterD3()

scatterD3(x = starwars$height, y = starwars$mass, lab = starwars$name);

Beyond interactive plots

R Markdown and shiny

Link with github